package pc;

import sun.java2d.cmm.lcms.LcmsServiceProvider;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author lyx
 * @Date 2021/6/23 10:23
 * 实现 A->C->B的线程顺序
 * Lock锁的消费者与生产者 await signal
 * condition 是 监视器
 */
public class OrderPCTest {
    public static void main(String[] args) {
        Data2 data = new Data2();

        new Thread(()->{
            for (int i = 0; i < 2; i++) {
                data.printA();
            }
        },"A").start();
        new Thread(()->{
            for (int i = 0; i < 2; i++) {
                data.printB();
            }
        },"B").start();
        new Thread(()->{
            for (int i = 0; i < 2; i++) {
                data.printC();
            }
        },"C").start();
    }

}





class Data2{

    private Lock lock = new ReentrantLock();
    private Condition condition1 = lock.newCondition();//监视器
    private Condition condition2 = lock.newCondition();
    private Condition condition3 = lock.newCondition();
    private int number = 1; //1A 2B 3C

    public void printA() {
        lock.lock();//加锁
        try {//业务
            while (number != 1){
                condition1.await(); //等待
            }
            System.out.println(Thread.currentThread().getName()+"=======>在运行");
            //唤醒指定的人,下面是唤醒B线程
            number = 3;
            condition3.signal();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
    public void printB() {
        lock.lock();
        try {//业务
            while(number!=2){
                //等待
                condition2.await();
            }
            System.out.println(Thread.currentThread().getName()+"=======>在运行");
            //精准唤醒
            number=1;
            condition1.signal();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
    public void printC() {
        lock.lock();
        try {
            while (number != 3){
                condition3.await();
            }
            System.out.println(Thread.currentThread().getName()+"=======>在运行");
            number=2;
            condition2.signal();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }

    }

}
